import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../modules/user'
import { asyncRoutes } from '../../router'
import router from '../../router'

export const usePermissionStore = defineStore('permission', () => {
  const isInitialized = ref(false)
  const routes = ref<RouteRecordRaw[]>([])
  const permissionCache = ref(new Map<string, boolean>())

  // 性能统计
  const performanceStats = ref({
    cacheHits: 0,
    cacheMisses: 0,
    totalChecks: 0,
    totalBuildTime: 0,
    lastBuildTime: 0
  })

  // 检查路由角色权限
  function checkRouteRoles(route: RouteRecordRaw, roles: string[]) {
    if (route.meta?.roles) {
      return roles.some((role) => Array.isArray(route.meta?.roles) && route.meta?.roles.includes(role))
    }
    return true
  }

  // 过滤路由
  function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]) {
    const res: RouteRecordRaw[] = []

    routes.forEach((route) => {
      const tmp = { ...route }
      if (checkRouteRoles(tmp, roles)) {
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        res.push(tmp)
      }
    })

    return res
  }

  // 构建路由
  async function buildRoutes(roles: string[]) {
    const startTime = performance.now()
    try {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }

      // 注册动态路由
      accessedRoutes.forEach((route) => {
        router.addRoute(route)
      })

      routes.value = accessedRoutes
      isInitialized.value = true

      // 记录构建时间
      const duration = performance.now() - startTime
      performanceStats.value.totalBuildTime += duration
      performanceStats.value.lastBuildTime = duration

      if (import.meta.env.DEV) {
        console.log(`[Permission] Routes built in ${duration.toFixed(2)}ms`)
      }
    } catch (error) {
      throw new Error('构建路由失败')
    }
  }

  // 检查权限（带缓存）
  function hasPermission(permissions: string | string[]) {
    const startTime = performance.now()
    const userStore = useUserStore()
    const userPermissions = userStore.userInfo?.permissions || []

    if (!permissions) return true
    if (userPermissions.includes('*')) return true

    // 生成缓存key
    const cacheKey = typeof permissions === 'string' ? permissions : permissions.join(',')

    // 命中缓存直接返回
    if (permissionCache.value.has(cacheKey)) {
      performanceStats.value.cacheHits++
      performanceStats.value.totalChecks++
      return permissionCache.value.get(cacheKey)
    }

    // 计算权限
    const hasPerm =
      typeof permissions === 'string'
        ? userPermissions.includes(permissions)
        : permissions.some((permission) => userPermissions.includes(permission))

    // 设置缓存
    permissionCache.value.set(cacheKey, hasPerm)
    performanceStats.value.cacheMisses++
    performanceStats.value.totalChecks++

    // 开发环境下输出性能统计
    if (import.meta.env.DEV) {
      const duration = performance.now() - startTime
      console.log(`[Permission] Check took ${duration.toFixed(2)}ms`)
      console.log(
        `[Permission] Cache hit rate: ${(
          (performanceStats.value.cacheHits / performanceStats.value.totalChecks) *
          100
        ).toFixed(2)}%`
      )
    }

    return hasPerm
  }

  // 清除权限缓存
  function clearPermissionCache() {
    permissionCache.value.clear()
  }

  // 监听用户权限变化
  const userStore = useUserStore()
  userStore.$subscribe(() => {
    clearPermissionCache()
  })

  return {
    routes,
    isInitialized,
    buildRoutes,
    hasPermission,
    clearPermissionCache,
    performanceStats
  }
})
